package pkg.andru.animation;

import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public abstract class AnimeDrawState implements IDrawState, Callback, IAnimeUpdate {

    static final String TAG = "AnimeDrawState";

    static final int MSG_START_ANIME = 1, MSG_STOP_ANIME = 2;

    int mFrameIndex;
    Handler mHandler;
    float px, py;
    boolean isLoop;
    Anime mAnime;

    public AnimeDrawState() {
        mHandler = new Handler(Looper.getMainLooper(), this);
        mFrameIndex = -1;
    }

    public float getPx() {
        return px;
    }

    public float getPy() {
        return py;
    }

    public void setPosition(float x, float y) {
        px = x;
        py = y;
    }

    public boolean isLoop() {
        return isLoop;
    }

    public void setLoop(boolean isLoop) {
        this.isLoop = isLoop;
    }

    public int getFrameIndex() {
        return mFrameIndex;
    }

    public void bindAnime(Anime anime) {
        mAnime = anime;
    }

    @Override
    public boolean handleMessage(Message msg) {
        final int what = msg.what;
        if (what == MSG_START_ANIME) {
            mFrameIndex++;
            int size = mAnime.getFrameCount();
            if (mFrameIndex == size) {
                if (isLoop) {
                    mFrameIndex %= size;
                    animeUpdate();
                    mHandler.sendEmptyMessageDelayed(MSG_START_ANIME, mAnime.getFrameDuration(mFrameIndex));
                } else {
                    mHandler.removeMessages(MSG_START_ANIME);
                }
            } else {
                animeUpdate();
                mHandler.sendEmptyMessageDelayed(MSG_START_ANIME, mAnime.getFrameDuration(mFrameIndex));
            }
        } else if (what == MSG_STOP_ANIME) {
            mHandler.removeMessages(MSG_START_ANIME);
            mFrameIndex = -1;
        }
        return true;
    }

    public void startAnime() {
        startAnime(0);
    }

    public void startAnime(int delay) {
        if (!mHandler.hasMessages(MSG_START_ANIME)) {
            Log.i(TAG, "send start anime");
            mHandler.sendEmptyMessageDelayed(MSG_START_ANIME, delay);
        }
    }

    public void stopAnime() {
        mHandler.removeMessages(MSG_START_ANIME);
        mHandler.sendEmptyMessage(MSG_STOP_ANIME);
    }

}